const http = require("http")
const fs = require("fs")
const url = require("url")
const qs = require("querystring")

http.createServer((req, res) => {
    if (req.url.includes("/api")) {
        dataRequest(req, res);
    } else {
        fileRequest(req, res);
    }
}).listen(3000, () => {
    console.log("服务器开启成功")
})

function fileRequest(req, res) {
    const p = url.parse(req.url).pathname;
    fs.readFile("./www" + p, (err, data) => {
        if (err) {
            res.write("404");
        } else {
            res.write(data);
        }
        res.end();
    })
}

function dataRequest(req, res) {
    if (req.method === "GET") {
        const data = url.parse(req.url, true).query
        transit(req, res, data)
    } else if (req.method === "POST") {
        let str = ""
        req.on("data", d => {
            str += d;
        })
        req.on("end", () => {
            const data = qs.parse(str);
            transit(req, res, data)
        })
    }
}

function transit(req, res, data) {
    switch (data.type) {
        case "getGoods":
            getGoods(req, res, data);
            break;
        case "getDetail":
            getDetail(req, res, data);
            break;
        default:
            err(req, res, data);
    }
}

function getDetail(req, res, reqData) {
    fs.readFile("./databases/goods.json", "utf-8", (err, data) => {
        if (err) {
            obj.code = 0;
            obj.title = "读取失败";
            obj.data = {};
            res.write(JSON.stringify(obj));
            res.end()
        } else {
            const goodsData = JSON.parse(data);
            let i = null;
            goodsData.some((val, idx) => {
                i = idx;
                return val.sku == reqData.id
            })
            const obj = {};
            if (i === null) {
                obj.code = 2;
                obj.title = "当前商品不存在";
                obj.data = {};
            } else {
                obj.code = 1;
                obj.title = "读取单个商品成功";
                obj.data = goodsData[i];
            }
            res.write(JSON.stringify(obj));
            res.end()
        }
    })
}

function getGoods(req, res, data) {
    fs.readFile("./databases/goods.json", "utf-8", (err, data) => {
        const obj = {};
        if (err) {
            obj.code = 0;
            obj.title = "读取失败";
            obj.data = [];
        } else {
            obj.code = 1;
            obj.title = "读取成功";
            obj.data = JSON.parse(data);
        }
        res.write(JSON.stringify(obj));
        res.end()
    })
}

function err(req, res, data) {
    console.log("err", data)
    res.end()
}